<?php

$auth = Auth::getAuth('current_user');
$db = new Database;
$fs = new functions();
$date = $fs->currentDateTime();

$content = json_decode($_GET['content'], true);

$application_id = $_GET['application_id'];
$object_type = $content['object_type'];
$object_id = $content['object_id'];

$applicationDoc = new Application($db, $application_id);
$personDoc = new Person($db, $auth['id']);

$dashboards = functions::getDashboards(" WHERE UserID = {$auth['id']} AND ApplicationID = {$application_id}");


if ($_GET['action'] == 'sorting') {
    foreach ($dashboards as $dashboardDoc) {
        $dashboardDoc->application = $applicationDoc;
        $dashboardDoc->content = $_GET['content'];
        $dashboardDoc->user = $personDoc;
        $dashboardDoc->modifier = $personDoc;
        $dashboardDoc->date_updated = $date;
        $dashboardDoc->update();
    }
} else {
    if (count($dashboards) == 0) {
        //create new dashboard for the user 
        $dashboardDoc = new Dashboard($db);
        $dashboardDoc->application = $applicationDoc;

        $content_arr = json_decode('[{"object_type":"widget","object_id":"widget"}]', true);
        array_push($content, $content_arr[0]);
        $content = functions::my_array_unique($content);
        $dashboardDoc->content = json_encode($content);

        $dashboardDoc->user = $personDoc;
        $dashboardDoc->creator = $personDoc;
        $dashboardDoc->modifier = $personDoc;
        $dashboardDoc->date_created = $date;
        $dashboardDoc->date_updated = $date;
        $dashboardDoc->save();
    } else {
        //update existing dashboard
        foreach ($dashboards as $dashboardDoc) {

            $dashboardDoc->application = $applicationDoc;
            $content_arr = json_decode($dashboardDoc->content, true);

            array_push($content_arr, $content[0]);
            
            $content_arr= functions::my_array_unique($content_arr);
            
            $dashboardDoc->content = json_encode($content_arr);
            $dashboardDoc->user = $personDoc;
            $dashboardDoc->modifier = $personDoc;
            $dashboardDoc->date_updated = $date;
            $dashboardDoc->update();
        }
    }
}



//
?>